//
//  JNCardSDKCommonWebView.m
//  TwoOneEight
//
//  Created by Jinniu on 2018/10/12.
//  Copyright © 2018年 Jinniu. All rights reserved.
//

#import "JNCardSDKCommonWebView.h"
#import <WebKit/WebKit.h>
#import "JNCardSDKLianDongResultVC.h"
@interface JNCardSDKCommonWebView ()<WKNavigationDelegate, WKUIDelegate,WKScriptMessageHandler>{
    int _currentIdx;
    NSTimer * _timer;
    NSInteger _count;
    UILabel * _timeLab;
}
@property (nonatomic, strong) WKWebView *web;
@property (nonatomic, strong) UIProgressView *progressView;
@end

@implementation JNCardSDKCommonWebView

- (void)viewDidLoad {
    [super viewDidLoad];
    _currentIdx = self.openCount;
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(notifyToH5:) name:@"shareResultToWKWebView" object:nil];
    /*2019-07-22 17:25:38修改为加载网页
    if (!self.isProductDetails) {
        self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, self.isHideNavBar==YES?0: kTopHeight-1, IPHONE_WIDTH, 1)];
        self.progressView.backgroundColor = [UIColor blueColor];
        //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
        self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
        [self.view addSubview:self.progressView];
    }
     */
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, self.isHideNavBar==YES?0: kTopHeight-1, IPHONE_WIDTH, 1)];
    self.progressView.backgroundColor = [UIColor blueColor];
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view addSubview:self.progressView];
    [self createUI];
}
- (void)viewWillDisappear:(BOOL)animated{//告诉h5要关闭网页了，因为有在web里再开web的需求，所以h5需要知道是否关了网页
    [super viewWillDisappear:animated];
    if(self.openCount<=_currentIdx){
        //pop
        [self.web evaluateJavaScript:[NSString stringWithFormat:@"closeCallBack('%d')",self.openCount] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        }];
    }
}
-(void)notifyToH5:(NSNotification *)notiy{
    NSDictionary * dic = [notiy userInfo];
    NSString * str = [[dic objectForKey:@"isSuccess"] isEqualToString:@"yes"]==YES?@"true":@"false";
    [self.web evaluateJavaScript:[NSString stringWithFormat:@"shareOk(%@)",str] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        
    }];
}

-(void)createUI{
    WKWebViewConfiguration *config = [WKWebViewConfiguration new];
    config.userContentController = [WKUserContentController new];
    //注册js方法
    [config.userContentController addScriptMessageHandler:self name: @"getStatusHeight"];
    [config.userContentController addScriptMessageHandler:self name: @"openWebView"];
    [config.userContentController addScriptMessageHandler:self name: @"closePage"];
    [config.userContentController addScriptMessageHandler:self name: @"webPhoneCall"];
    self.web = [[WKWebView alloc]initWithFrame:CGRectZero configuration:config];
    _web.navigationDelegate = self;
    
    [self.view addSubview:self.web];
    if (self.isHideStatueBar) {
        _web.sd_layout.leftEqualToView(self.view).rightEqualToView(self.view).topSpaceToView(self.view, self.isHideNavBar==YES?0:kNavBarHeight).bottomSpaceToView(self.view, KTabbarSafeBottomMargin);
    }else{
        _web.sd_layout.leftEqualToView(self.view).rightEqualToView(self.view).topSpaceToView(self.view, self.isHideNavBar==YES?kStatusBarHeight:kTopHeight).bottomSpaceToView(self.view, KTabbarSafeBottomMargin);
    }
    [_web addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [_web addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];

    if (self.htmlStr.length==0) {
        NSString * finalStr = self.url;
        if ([JNCardSDKMytools IsChinese:self.url]==YES) {
            finalStr = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
        NSURLRequest * req = [NSURLRequest requestWithURL:[NSURL URLWithString:finalStr]];
        [_web loadRequest:req];
    }else{
        [_web loadHTMLString:self.htmlStr baseURL:nil];
    }
    if (@available(iOS 11.0, *)) {
        _web.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

//设置文本字体大小
//- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
//    [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '300%'" completionHandler:nil];
//}
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    VLog(@"开始加载%@",[webView.URL absoluteString]);
    NSString * urlStr = [webView.URL absoluteString];
    if([urlStr containsString:@"https://itunes.apple.com"]){
        [[UIApplication sharedApplication] openURL:webView.URL];
    }
    
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    VLog(@"加载完成");
    //加载完成后隐藏progressView
    self.progressView.hidden = YES;
    if (self.isCreditCardVC) {
        self.myTitle = [webView title];
    }
}

//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    VLog(@"加载失败");
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    VLog(@"方法名:%@，传递的数据：%@",message.name,message.body);// 方法名
    if ([message.name isEqualToString:@"closePage"]) {
        [self.navigationController popViewControllerAnimated:YES];
    }else if ([message.name isEqualToString:@"webPhoneCall"]){
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",message.body];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }else if ([message.name isEqualToString:@"openWebView"]){
        NSDictionary * dic = [JNCardSDKMytools dictionaryWithJsonString:message.body];
        BOOL isStatue = [dic[@"statusBar"] boolValue]?YES:NO;
        BOOL isNav = [dic[@"navBar"] boolValue]?YES:NO;
        JNCardSDKCommonWebView * web = [JNCardSDKCommonWebView new];
        web.openCount = self.openCount ++;
        web.url = dic[@"url"];
        web.isHideStatueBar = !isStatue;
        web.isHideNavBar = !isNav;
        [self.navigationController pushViewController:web animated:YES];
    }else if ([message.name isEqualToString:@"getStatusHeight"]){//h5向APP请求状态栏高度
        [self sendStatueBarHeightToH5];
    }
}

-(void)sendStatueBarHeightToH5{//APP返回状态栏高度给h5
    [self.web evaluateJavaScript:[NSString stringWithFormat:@"setStatusHeight('%lf')",kStatusBarHeight] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
    }];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    // ------  对alipays:相关的scheme处理 -------
    // 若遇到支付宝相关scheme，则跳转到本地支付宝App
    NSString *reqUrl = navigationAction.request.URL.absoluteString;
    if ([reqUrl containsString: @"https://mcashier.95516.com/mobile/authPay/callback.action"]||[reqUrl containsString: @"http://epay.gaohuitong.com:8083/interfaceWeb/appBindCard/dealQbyFrontBindReturn"]) {
        //这边本来是下面那个的5秒钟代码，现在去掉废弃了（2018-8-31）
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }else if([reqUrl isEqualToString:@"http://www.yuntianpay.net/web/success.html"]){
        _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerfie) userInfo:nil repeats:YES];
        _count = 5;
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
        _timeLab = [UILabel labelWithTitle:@"银联认证通讯中，请等待...(5s)" color:[UIColor blackColor] fontSize:14 alignment:NSTextAlignmentCenter];
        _timeLab.frame = Frame(0, IPHONE_HEIGHT/2+50, IPHONE_WIDTH, 30);
        UIWindow * w = [UIApplication sharedApplication].delegate.window;
        [w addSubview:_timeLab];
        [self notify];
        self.isHideLeftBtn = YES;
//        _canBack = YES;
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    if ([reqUrl hasPrefix:@"alipays://"] || [reqUrl hasPrefix:@"alipay://"]) {
        // 跳转支付宝App
        BOOL bSucc = [[UIApplication sharedApplication]openURL:navigationAction.request.URL];
        // 如果跳转失败，则跳转itune下载支付宝App
        if (!bSucc) {
            [self alertControllerWithMessage:@"未检测到支付宝客户端，请您安装后重试。"];
        }
    }
    // 确认可以跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}
-(void)notify{
    [SVProgressHUD show];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    NSNotification * message = [[NSNotification alloc]initWithName:@"createPlanDirectly" object:self userInfo:nil];
    [center postNotification:message];
}
- (void)timerfie {
    if (_count == 0) {
        [SVProgressHUD dismiss];
        [_timer invalidate];
        [_timeLab removeFromSuperview];
        self.isHideLeftBtn = NO;
        if (self.isGoToSMSVerify) {
            JNCardSDKLianDongResultVC * vc = [JNCardSDKLianDongResultVC new];//2018-8-29改为这个控制器
            vc.cardModel = self.cardModel;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            if (self.successBlock) {
                self.successBlock();
            }
        }
        [self backClick];//返回界面
    }
    _count--;
    _timeLab.text = [NSString stringWithFormat:@"银联认证通讯中，请等待...(%lds)",_count];
}

- (void)alertControllerWithMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"立即安装" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // NOTE: 跳转itune下载支付宝App
        NSString* urlStr = @"https://itunes.apple.com/cn/app/zhi-fu-bao-qian-bao-yu-e-bao/id333206289?mt=8";
        NSURL *downloadUrl = [NSURL URLWithString:urlStr];
        [[UIApplication sharedApplication]openURL:downloadUrl];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark 进度条处理箱
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.web.estimatedProgress;
        if (self.progressView.progress == 1) {
            /*
             *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的合伙人中会恢复为1.5倍
             *动画时长0.25s，延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
            }];
        }
    }else if ([keyPath isEqualToString:@"title"]) {
        if (object == _web){
            if ((self.isCreditCardVC)) {
                self.myTitle = _web.title;
            }
        }else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
- (void)dealloc {
    [self.web removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.web removeObserver:self forKeyPath:@"title" context:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(NSString*)objToString:(id)obj{
    NSError * error;
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:obj options:kNilOptions error:&error];
    NSString * jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonStr;
}
@end
